<?php

namespace App\Http\Controllers;

use App\Models\Channel;
use App\Models\Order;
use App\Services\PayNotifyService;
use App\Services\PayService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class PayController extends Controller
{
    public function pay(Order $order, PayService $payService)
    {
        $channel = $order->channel;
        if (is_null($channel) || $channel->status == Channel::STATUS_STOPPED) {
            if (\request()->isJson()) {
                return response()->json([
                    'code' => 400,
                    'message' => '支付通道错误'
                ]);
            }
            return redirect()->route('error.message')->withErrors('当前支付通道不可用');
        }
        if ($order->status !== Order::STATUS_UNPAID) {
            if (\request()->isJson()) {
                return response()->json([
                    'code' => 400,
                    'message' => '订单状态异常'
                ]);
            }
            return redirect()->route('error.message')->withErrors('当前订单状态不允许支付');
        }
        return $payService->pay($order);
    }

    public function notify($gateway, Channel $channel, PayNotifyService $payNotifyService)
    {
        return $payNotifyService->notify($gateway, $channel);
    }

    public function return($gateway, Order $order, PayNotifyService $payNotifyService)
    {
        if (Str::contains(rtrim($order->notify_url, '?'), '?')) {
            $url = rtrim($order->return_url, '?') . '&' . urldecode(http_build_query($payNotifyService->getNotifyParams($order)));
        } else {
            $url = rtrim($order->return_url, '?') . '?' . urldecode(http_build_query($payNotifyService->getNotifyParams($order)));
        }
        return redirect($url);
    }

    public function status(Order $order)
    {
        $status = $order->status;
        return response()->json(compact('status'));
    }
}
